{% extends "base.html" %}

{% block title %}系统设置 - XbyJob{% endblock %}

{% block extra_head %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
{% endblock %}

{% block content %}
<!-- 页面头部 -->
<div class="settings-header mb-4">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h1 class="h2 mb-1">
                <i class="fas fa-cogs text-primary me-2"></i>系统设置
            </h1>
            <p class="text-muted mb-0">管理系统配置、监控资源使用情况和查看系统信息</p>
        </div>
        <div class="settings-actions">
            <button class="btn btn-outline-primary btn-sm" onclick="location.reload()">
                <i class="fas fa-sync-alt me-1"></i>刷新
            </button>
        </div>
    </div>
</div>

<div class="row g-4">
    <!-- 左侧主要内容区 -->
    <div class="col-lg-6">
        {% if current_user.is_admin %}
        <!-- 系统配置卡片 -->
        <div class="settings-card mb-4">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-simple-primary border-0">
                    <div class="d-flex align-items-center">
                        <div class="settings-icon me-3">
                            <i class="fas fa-cog"></i>
                        </div>
                        <div>
                            <h5 class="mb-0">系统配置</h5>
                            <small class="opacity-90">配置系统运行参数</small>
                        </div>
                    </div>
                </div>
                <div class="card-body p-4">
                    <form id="systemConfigForm">
                        <div class="row g-4">
                            <div class="col-md-6">
                                <div class="config-item">
                                    <label for="logRetentionDays" class="form-label fw-semibold">
                                        <i class="fas fa-file-alt text-info me-2"></i>日志保留天数
                                    </label>
                                    <div class="input-group">
                                        <input type="number" class="form-control" id="logRetentionDays" 
                                               value="30" min="1" max="365" placeholder="输入天数">
                                        <span class="input-group-text">天</span>
                                    </div>
                                    <div class="form-text">
                                        <i class="fas fa-info-circle me-1"></i>系统日志自动清理周期，建议保留30-90天
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="config-item">
                                    <label for="executionRetentionDays" class="form-label fw-semibold">
                                        <i class="fas fa-history text-success me-2"></i>执行记录保留天数
                                    </label>
                                    <div class="input-group">
                                        <input type="number" class="form-control" id="executionRetentionDays" 
                                               value="90" min="1" max="365" placeholder="输入天数">
                                        <span class="input-group-text">天</span>
                                    </div>
                                    <div class="form-text">
                                        <i class="fas fa-info-circle me-1"></i>任务执行记录自动清理周期，建议保留90-180天
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-flex justify-content-end mt-4 pt-3 border-top">
                            <button type="button" class="btn btn-primary px-4" onclick="saveSystemConfig()">
                                <i class="fas fa-save me-2"></i>保存配置
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 调度器管理卡片 -->
        <div class="settings-card mb-4">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-simple-info border-0">
                    <div class="d-flex align-items-center">
                        <div class="settings-icon me-3">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div>
                            <h5 class="mb-0">调度器管理</h5>
                            <small class="opacity-90">监控和管理任务调度器</small>
                        </div>
                    </div>
                </div>
                <div class="card-body p-4">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <div class="action-card h-100">
                                <div class="d-flex align-items-center mb-3">
                                    <div class="action-icon bg-primary bg-opacity-10 text-primary me-3">
                                        <i class="fas fa-play-circle"></i>
                                    </div>
                                    <div>
                                        <h6 class="mb-0">运行中任务</h6>
                                        <small class="text-muted">查看当前正在执行的任务</small>
                                    </div>
                                </div>
                                <button type="button" class="btn btn-outline-primary w-100" onclick="viewRunningTasks()">
                                    <i class="fas fa-list me-2"></i>查看运行中任务
                                </button>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="action-card h-100">
                                <div class="d-flex align-items-center mb-3">
                                    <div class="action-icon bg-warning bg-opacity-10 text-warning me-3">
                                        <i class="fas fa-clock"></i>
                                    </div>
                                    <div>
                                        <h6 class="mb-0">等待队列</h6>
                                        <small class="text-muted">查看等待执行的任务队列</small>
                                    </div>
                                </div>
                                <button type="button" class="btn btn-outline-warning w-100" onclick="viewPendingTasks()">
                                    <i class="fas fa-hourglass-half me-2"></i>查看等待任务
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>


        <!-- 统计信息卡片 -->
        <div class="settings-card">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-simple-dark border-0">
                    <div class="d-flex align-items-center">
                        <div class="settings-icon me-3">
                            <i class="fas fa-chart-bar"></i>
                        </div>
                        <div>
                            <h5 class="mb-0">统计概览</h5>
                            <small class="opacity-90">系统运行统计</small>
                        </div>
                    </div>
                </div>
                <div class="card-body p-4">
                    <div class="row g-3">
                        <div class="col-6">
                            <div class="stat-item text-center">
                                <div class="stat-icon bg-primary bg-opacity-10 text-primary mb-2">
                                    <i class="fas fa-tasks"></i>
                                </div>
                                <h5 class="mb-0 text-primary" id="totalTasks">0</h5>
                                <small class="text-muted">总任务数</small>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="stat-item text-center">
                                <div class="stat-icon bg-success bg-opacity-10 text-success mb-2">
                                    <i class="fas fa-play"></i>
                                </div>
                                <h5 class="mb-0 text-success" id="activeTasks">0</h5>
                                <small class="text-muted">活跃任务</small>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="stat-item text-center">
                                <div class="stat-icon bg-info bg-opacity-10 text-info mb-2">
                                    <i class="fas fa-history"></i>
                                </div>
                                <h5 class="mb-0 text-info" id="totalExecutions">0</h5>
                                <small class="text-muted">总执行次数</small>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="stat-item text-center">
                                <div class="stat-icon bg-warning bg-opacity-10 text-warning mb-2">
                                    <i class="fas fa-percentage"></i>
                                </div>
                                <h5 class="mb-0 text-warning" id="successRate">0%</h5>
                                <small class="text-muted">成功率</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {% endif %}
    </div>

    <!-- 右侧信息区域 -->
    <div class="col-lg-6">
        <!-- 系统信息卡片 -->
        <div class="info-card mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-simple-success border-0">
                    <div class="d-flex align-items-center">
                        <div class="info-icon me-3">
                            <i class="fas fa-server"></i>
                        </div>
                        <div>
                            <h6 class="mb-0">系统信息</h6>
                            <small class="opacity-90">服务器运行状态</small>
                        </div>
                    </div>
                </div>
                <div class="card-body p-4">
                    <div id="systemInfo">
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <div class="mt-2 text-muted">正在加载系统信息...</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 资源使用情况卡片 -->
        <div class="info-card mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-simple-warning border-0">
                    <div class="d-flex align-items-center">
                        <div class="info-icon me-3">
                            <i class="fas fa-chart-pie"></i>
                        </div>
                        <div>
                            <h6 class="mb-0">资源监控</h6>
                            <small class="opacity-90">实时资源使用情况</small>
                        </div>
                    </div>
                </div>
                <div class="card-body p-4">
                    <div class="resource-item mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="fw-semibold">
                                <i class="fas fa-microchip text-primary me-2"></i>CPU使用率
                            </span>
                            <span class="badge bg-primary" id="cpuBadge">0%</span>
                        </div>
                        <div class="progress progress-modern">
                            <div class="progress-bar bg-gradient-primary" role="progressbar" id="cpuUsage" style="width: 0%"></div>
                        </div>
                    </div>
                    
                    <div class="resource-item mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="fw-semibold">
                                <i class="fas fa-memory text-warning me-2"></i>内存使用率
                            </span>
                            <span class="badge bg-warning" id="memoryBadge">0%</span>
                        </div>
                        <div class="progress progress-modern">
                            <div class="progress-bar bg-gradient-warning" role="progressbar" id="memoryUsage" style="width: 0%"></div>
                        </div>
                    </div>
                    
                    <div class="resource-item">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="fw-semibold">
                                <i class="fas fa-hdd text-info me-2"></i>磁盘使用率
                            </span>
                            <span class="badge bg-info" id="diskBadge">0%</span>
                        </div>
                        <div class="progress progress-modern">
                            <div class="progress-bar bg-gradient-info" role="progressbar" id="diskUsage" style="width: 0%"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>



        <!-- 关于项目卡片 -->
        <div class="info-card">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-simple-secondary border-0">
                    <div class="d-flex align-items-center">
                        <div class="info-icon me-3">
                            <i class="fas fa-info-circle"></i>
                        </div>
                        <div>
                            <h6 class="mb-0">关于项目</h6>
                            <small class="opacity-90">系统版本信息</small>
                        </div>
                    </div>
                </div>
                <div class="card-body p-4 text-center">
                    <div class="about-content">
                        <div class="project-logo mb-3">
                            <i class="fas fa-code fa-3x text-primary"></i>
                        </div>
                        <h6 class="fw-bold mb-2">XbyJob 任务调度系统</h6>
                        <p class="text-muted small mb-3">
                            基于 Python Flask 的分布式任务调度平台<br>
                            提供高效、可靠的任务管理解决方案
                        </p>
                        <a href="{{ url_for('dashboard.about') }}" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-external-link-alt me-1"></i>了解更多
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 运行中任务模态框 -->
<div class="modal fade" id="runningTasksModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">运行中任务</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-striped" id="runningTasksTable">
                        <thead>
                            <tr>
                                <th>任务名称</th>
                                <th>执行ID</th>
                                <th>开始时间</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td colspan="4" class="text-center">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 等待任务模态框 -->
<div class="modal fade" id="pendingTasksModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">执行队列等待任务</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-striped" id="pendingTasksTable">
                        <thead>
                            <tr>
                                <th>任务名称</th>
                                <th>任务ID</th>
                                <th>提交时间</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td colspan="5" class="text-center">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<style>
/* 简约设置页面样式 */
.settings-header {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 12px;
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.settings-header h1 {
    color: #495057;
    font-weight: 600;
}

.settings-header p {
    color: #6c757d;
}

/* 简约卡片样式 */
.settings-card .card,
.info-card .card {
    border-radius: 12px;
    transition: all 0.2s ease;
    border: 1px solid #e9ecef;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.settings-card .card:hover,
.info-card .card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 简约背景色 */
.bg-simple-primary {
    background: #007bff;
    color: white !important;
}

.bg-simple-primary * {
    color: white !important;
}

.bg-simple-info {
    background: #17a2b8;
    color: white !important;
}

.bg-simple-info * {
    color: white !important;
}

.bg-simple-success {
    background: #28a745;
    color: white !important;
}

.bg-simple-success * {
    color: white !important;
}

.bg-simple-warning {
    background: #f39c12;
    color: #ffffff !important;
}

.bg-simple-warning * {
    color: #ffffff !important;
}

.bg-simple-dark {
    background: #343a40;
    color: white !important;
}

.bg-simple-dark * {
    color: white !important;
}

.bg-simple-secondary {
    background: #6c757d;
    color: white !important;
}

.bg-simple-secondary * {
    color: white !important;
}

/* 改善文字可读性 */
.text-muted {
    color: #495057 !important;
}

.opacity-90 {
    opacity: 0.9 !important;
}

/* 确保白色背景上的文字可见性 */
.card-body {
    color: #212529 !important;
}

.card-body * {
    color: inherit !important;
}

.card-body .text-muted {
    color: #495057 !important;
    font-weight: 500 !important;
}

/* 统计概览区域特殊样式 */
.stat-item .text-muted {
    color: #343a40 !important;
    font-weight: 600 !important;
    font-size: 0.875rem !important;
}

.stat-item h5 {
    font-weight: 700 !important;
    font-size: 1.5rem !important;
}

/* 增强统计图标的可见性 */
.stat-icon {
    width: 48px !important;
    height: 48px !important;
    border-radius: 12px !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    margin: 0 auto !important;
}

.stat-icon i {
    font-size: 1.25rem !important;
}

/* 统计概览卡片整体优化 */
.stat-item {
    padding: 1rem !important;
    border-radius: 8px !important;
    background: rgba(255, 255, 255, 0.8) !important;
    border: 1px solid rgba(0, 0, 0, 0.1) !important;
    transition: all 0.3s ease !important;
}

.stat-item:hover {
    background: rgba(255, 255, 255, 0.95) !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
    transform: translateY(-2px) !important;
}

/* 确保标题文字清晰可见 */
.card-header h5 {
    color: #212529 !important;
    font-weight: 600 !important;
}

.card-header small {
    color: #495057 !important;
    font-weight: 500 !important;
}

.card-body .form-label {
    color: #212529 !important;
}

.card-body .form-text {
    color: #6c757d !important;
}

/* 确保所有普通文字在白色背景上可见 */
body {
    color: #212529;
}

.card {
    color: #212529;
}

/* 简约图标样式 */
.settings-icon,
.info-icon {
    width: 45px;
    height: 45px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255, 255, 255, 0.9);
    font-size: 1.3rem;
    color: #343a40 !important;
}

.action-icon,
.stat-icon {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.1rem;
}

/* 配置项样式 */
.config-item {
    padding: 1.5rem;
    background: #ffffff;
    border-radius: 12px;
    border: 2px solid #e9ecef;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.config-item:hover {
    background: #f8f9fa;
    border-color: #007bff;
    box-shadow: 0 4px 12px rgba(0, 123, 255, 0.15);
}

.config-item .form-label {
    color: #212529;
    font-weight: 600;
    margin-bottom: 0.75rem;
}

.config-item .input-group {
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    overflow: hidden;
}

.config-item .form-control {
    border: none;
    padding: 0.75rem 1rem;
    font-size: 0.95rem;
}

.config-item .input-group-text {
    background: #e9ecef;
    border: none;
    color: #6c757d;
    font-weight: 500;
}

/* 操作卡片样式 */
.action-card {
    padding: 1.5rem;
    background: #ffffff;
    border: 1px solid #e9ecef;
    border-radius: 12px;
    transition: all 0.3s ease;
}

.action-card:hover {
    background: #f8f9fa;
    border-color: #dee2e6;
    transform: translateY(-2px);
}

/* 资源监控样式 */
.resource-item {
    padding: 1rem;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 10px;
    backdrop-filter: blur(10px);
}

.progress-modern {
    height: 8px;
    border-radius: 10px;
    background: rgba(255, 255, 255, 0.2);
    overflow: hidden;
}

.progress-modern .progress-bar {
    border-radius: 10px;
    transition: width 0.6s ease;
}

/* 统计项样式 */
.stat-item {
    padding: 1rem;
    border-radius: 10px;
    transition: all 0.3s ease;
}

.stat-item:hover {
    transform: scale(1.05);
}

.stat-item h5 {
    font-weight: 700;
    font-size: 1.5rem;
}

/* 关于项目样式 */
.about-content {
    padding: 1rem;
}

.project-logo {
    padding: 1rem;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 50%;
    width: 80px;
    height: 80px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: center;
}

.project-logo i {
    color: white;
}

/* 简约按钮样式 */
.btn {
    border-radius: 6px;
    font-weight: 500;
    transition: all 0.2s ease;
}

.btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.btn-primary {
    background: #007bff;
    border-color: #007bff;
}

.btn-primary:hover {
    background: #0056b3;
    border-color: #0056b3;
}

.btn-outline-primary {
    border-color: #007bff;
    color: #007bff;
}

.btn-outline-primary:hover {
    background: #007bff;
    border-color: #007bff;
    color: white !important;
}

.btn-outline-warning {
    border-color: #ffc107;
    color: #ffc107;
}

.btn-outline-warning:hover {
    background: #ffc107;
    border-color: #ffc107;
    color: #212529 !important;
}

/* 徽章样式 */
.badge {
    font-weight: 500;
    padding: 0.5rem 0.75rem;
    border-radius: 6px;
}

/* 系统信息样式 */
#systemInfo p {
    margin-bottom: 0.75rem;
    padding: 0.5rem 0;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

#systemInfo p:last-child {
    border-bottom: none;
}

#systemInfo strong {
    color: rgba(255, 255, 255, 0.9);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .settings-header {
        padding: 1.5rem;
        text-align: center;
    }
    
    .settings-header .d-flex {
        flex-direction: column;
        gap: 1rem;
    }
    
    .config-item,
    .action-card {
        padding: 1rem;
    }
    
    .stat-item {
        margin-bottom: 1rem;
    }
}

/* 加载动画增强 */
.spinner-border {
    width: 3rem;
    height: 3rem;
}

/* 鼠标悬停效果 */
.cursor-pointer {
    cursor: pointer;
}

.cursor-pointer:hover {
    opacity: 0.8;
}

/* 卡片头部文字样式 */
.card-header h5,
.card-header h6 {
    font-weight: 600;
}

.card-header small {
    font-weight: 400;
}

/* 表单文本样式 */
.form-text {
    font-size: 0.85rem;
    color: #6c757d;
    margin-top: 0.5rem;
}

/* 边框顶部样式 */
.border-top {
    border-top: 1px solid #e9ecef !important;
}

/* 间距调整 */
.g-4 > * {
    padding: 0.75rem;
}

/* 阴影效果 */
.shadow-sm {
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075) !important;
}
</style>
<script>
$(document).ready(function() {
    loadSystemInfo();
    loadStatistics();
    loadSystemConfig();
    
    // 定期更新资源使用情况
    setInterval(function() {
        loadSystemInfo();
    }, 15000);
});

function loadSystemInfo() {
    $.get('/dashboard/api/system/status')
        .done(function(response) {
            if (response.success) {
                renderSystemInfo(response.data.system_info);
                updateResourceUsage(response.data.system_info);
            }
        })
        .fail(function() {
            $('#systemInfo').html('<div class="text-danger">加载失败</div>');
        });
}

function renderSystemInfo(info) {
    const html = `
        <p><strong>操作系统:</strong> ${info.platform || '-'}</p>
        <p><strong>Python版本:</strong> ${info.python_version || '-'}</p>
        <p><strong>CPU核心数:</strong> ${info.cpu_count || '-'}</p>
        <p><strong>总内存:</strong> ${formatBytes(info.total_memory) || '-'}</p>
        <p><strong>启动时间:</strong> ${info.boot_time ? new Date(info.boot_time).toLocaleString() : '-'}</p>
    `;
    $('#systemInfo').html(html);
}



function loadStatistics() {
    $.get('/api/stats/overview')
        .done(function(response) {
            if (response.success) {
                const data = response.data;
                $('#totalTasks').text(data.total_tasks);
                $('#activeTasks').text(data.active_tasks);
                $('#totalExecutions').text(data.total_executions);
                $('#successRate').text(data.success_rate + '%');
            }
        });
}

function loadSystemConfig() {
    $.get('/api/system/config')
        .done(function(response) {
            if (response.success) {
                const config = response.data;
                $('#logRetentionDays').val(config.log_retention_days || 30);
                $('#executionRetentionDays').val(config.execution_retention_days || 90);
            }
        })
        .fail(function() {
            console.log('加载系统配置失败，使用默认值');
        });
}

function updateResourceUsage(systemInfo) {
    if (systemInfo) {
        const cpuPercent = systemInfo.cpu_percent || 0;
        const memoryPercent = systemInfo.memory_percent || 0;
        const diskPercent = systemInfo.disk_percent || 0;
        
        // 更新进度条
        $('#cpuUsage').css('width', cpuPercent + '%').text(cpuPercent.toFixed(1) + '%');
        $('#memoryUsage').css('width', memoryPercent + '%').text(memoryPercent.toFixed(1) + '%');
        $('#diskUsage').css('width', diskPercent + '%').text(diskPercent.toFixed(1) + '%');
        
        // 更新徽章
        $('#cpuBadge').text(cpuPercent.toFixed(1) + '%');
        $('#memoryBadge').text(memoryPercent.toFixed(1) + '%');
        $('#diskBadge').text(diskPercent.toFixed(1) + '%');
    }
}



function saveSystemConfig() {
    const config = {
        log_retention_days: parseInt($('#logRetentionDays').val()),
        execution_retention_days: parseInt($('#executionRetentionDays').val())
    };
    
    // 验证输入
    
    if (config.log_retention_days < 1 || config.log_retention_days > 365) {
        showAlert('日志保留天数必须在1-365之间', 'danger');
        return;
    }
    
    if (config.execution_retention_days < 1 || config.execution_retention_days > 365) {
        showAlert('执行记录保留天数必须在1-365之间', 'danger');
        return;
    }
    
    // 发送配置到后端
    $.ajax({
        url: '/api/system/config',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(config)
    })
    .done(function(response) {
        if (response.success) {
            showAlert('配置保存成功', 'success');
        } else {
            showAlert('保存失败: ' + response.message, 'danger');
        }
    })
    .fail(function() {
        showAlert('网络错误，请稍后重试', 'danger');
    });
}







function viewRunningTasks() {
    $('#runningTasksModal').modal('show');
    
    // 显示加载状态
    $('#runningTasksTable tbody').html(`
        <tr><td colspan="5" class="text-center">加载中...</td></tr>
    `);
    
    // 加载运行中任务
    $.ajax({
        url: '/api/services/executor/running',
        type: 'GET',
        timeout: 10000, // 10秒超时
        cache: false
    })
    .done(function(response) {
        if (response.success) {
            renderRunningTasks(response.data);
        } else {
            $('#runningTasksTable tbody').html(`
                <tr><td colspan="5" class="text-center text-danger">获取失败: ${response.message}</td></tr>
            `);
        }
    })
    .fail(function(xhr, status, error) {
        console.log('Running tasks request failed:', status, error);
        let errorMsg = '网络错误';
        if (status === 'timeout') {
            errorMsg = '请求超时，请稍后重试';
        } else if (status === 'error' && xhr.status === 0) {
            errorMsg = '连接中断，请检查网络';
        }
        $('#runningTasksTable tbody').html(`
            <tr><td colspan="5" class="text-center text-danger">${errorMsg}</td></tr>
        `);
    });
}

function renderRunningTasks(tasks) {
    const tbody = $('#runningTasksTable tbody');
    tbody.empty();
    
    if (tasks.length === 0) {
        tbody.append(`
            <tr>
                <td colspan="5" class="text-center text-muted">暂无运行中任务</td>
            </tr>
        `);
        return;
    }
    
    tasks.forEach(function(task) {
        tbody.append(`
            <tr>
                <td>${task.task_name || '-'}</td>
                <td><code>${task.execution_id}</code></td>
                <td>${task.started_at ? new Date(task.started_at).toLocaleString() : '-'}</td>
                <td><span class="badge bg-primary">运行中</span></td>
                <td>
                    <button type="button" class="btn btn-sm btn-danger" 
                            onclick="stopRunningTask('${task.execution_id}')" 
                            title="停止任务">
                        <i class="fas fa-stop"></i>
                    </button>
                </td>
            </tr>
        `);
    });
}

function formatBytes(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function stopRunningTask(executionId) {
    if (!confirm('确定要停止这个任务吗？')) {
        return;
    }
    
    // 显示停止中状态
    showAlert('正在停止任务...', 'info');
    
    $.ajax({
        url: `/api/executions/${executionId}/stop`,
        method: 'POST',
        contentType: 'application/json',
        headers: {
            'X-CSRFToken': $('meta[name=csrf-token]').attr('content')
        }
    })
    .done(function(response) {
        if (response.success) {
            // 等待一段时间后验证任务是否真的停止了
            setTimeout(function() {
                verifyTaskStopped(executionId);
            }, 2000); // 等待2秒后验证
        } else {
            showAlert('停止任务失败: ' + response.message, 'danger');
        }
    })
    .fail(function(xhr, status, error) {
        console.error('停止任务时发生错误:', error);
        let errorMessage = '停止任务时发生错误';
        if (xhr.responseJSON && xhr.responseJSON.message) {
            errorMessage += ': ' + xhr.responseJSON.message;
        } else {
            errorMessage += ': ' + error;
        }
        showAlert(errorMessage, 'danger');
    });
}

function verifyTaskStopped(executionId) {
    $.ajax({
        url: '/api/services/executor/running',
        type: 'GET',
        timeout: 5000,
        cache: false
    })
    .done(function(response) {
        if (response && response.success) {
            const runningTasks = response.data || [];
            const isStillRunning = runningTasks.some(task => task.execution_id === executionId);
            
            if (isStillRunning) {
                showAlert('任务停止失败，任务仍在运行中', 'warning');
            } else {
                showAlert('任务已成功停止', 'success');
            }
            
            // 刷新运行中任务列表
            viewRunningTasks();
        } else {
            showAlert('无法验证任务状态', 'warning');
            // 仍然刷新列表
            viewRunningTasks();
        }
    })
    .fail(function() {
        showAlert('验证任务状态失败，请手动刷新查看', 'warning');
        // 仍然刷新列表
        viewRunningTasks();
    });
}

function viewPendingTasks() {
    $('#pendingTasksModal').modal('show');
    loadPendingTasks();
}

function loadPendingTasks() {
    $.ajax({
        url: '/api/services/queue/pending',
        type: 'GET',
        timeout: 10000,
        cache: false
    })
    .done(function(response) {
        if (response.success) {
            renderPendingTasks(response.data);
        } else {
            $('#pendingTasksTable tbody').html(`
                <tr><td colspan="5" class="text-center text-danger">获取失败: ${response.message}</td></tr>
            `);
        }
    })
    .fail(function(xhr, status, error) {
        console.log('Pending tasks request failed:', status, error);
        let errorMsg = '网络错误';
        if (status === 'timeout') {
            errorMsg = '请求超时，请稍后重试';
        } else if (status === 'error' && xhr.status === 0) {
            errorMsg = '连接中断，请检查网络';
        }
        $('#pendingTasksTable tbody').html(`
            <tr><td colspan="5" class="text-center text-danger">${errorMsg}</td></tr>
        `);
    });
}

function renderPendingTasks(data) {
    const tbody = $('#pendingTasksTable tbody');
    tbody.empty();
    
    // 检查数据格式，API返回的是队列信息对象，不是任务数组
    if (!data || typeof data !== 'object') {
        tbody.append(`
            <tr>
                <td colspan="5" class="text-center text-danger">数据格式错误</td>
            </tr>
        `);
        return;
    }
    
    const totalPending = data.total_pending || 0;
    const reservedTasks = data.reserved_tasks || {};
    
    if (totalPending === 0) {
        tbody.append(`
            <tr>
                <td colspan="5" class="text-center text-muted">暂无等待任务</td>
            </tr>
        `);
        return;
    }
    
    // 显示队列统计信息
    tbody.append(`
        <tr>
            <td colspan="2"><strong>队列统计</strong></td>
            <td>${new Date().toLocaleString()}</td>
            <td><span class="badge bg-warning">等待中: ${totalPending}</span></td>
            <td>-</td>
        </tr>
    `);
    
    // 显示各个worker的保留任务
    Object.keys(reservedTasks).forEach(function(worker) {
        const tasks = reservedTasks[worker] || [];
        if (tasks.length > 0) {
            tasks.forEach(function(task, index) {
                tbody.append(`
                    <tr>
                        <td>${worker}</td>
                        <td><code>${task.name || task.id || 'Unknown'}</code></td>
                        <td>${new Date().toLocaleString()}</td>
                        <td><span class="badge bg-warning">等待中</span></td>
                        <td>
                            <span class="text-muted">队列任务</span>
                        </td>
                    </tr>
                `);
            });
        }
    });
}

function removePendingTask(taskId) {
    if (!confirm('确定要移除这个等待任务吗？')) {
        return;
    }
    
    $.ajax({
        url: `/api/tasks/${taskId}`,
        method: 'DELETE',
        contentType: 'application/json'
    })
    .done(function(response) {
        if (response.success) {
            showAlert('任务已移除', 'success');
            // 刷新等待任务列表
            loadPendingTasks();
        } else {
            showAlert('移除任务失败: ' + response.message, 'danger');
        }
    })
    .fail(function() {
        showAlert('网络错误，请稍后重试', 'danger');
    });
}



function showAlert(message, type) {
    // 使用基础模板中定义的全局showMessage函数（即showToast）
    if (typeof window.showMessage === 'function') {
        // 映射类型到Toast支持的类型
        let toastType = type;
        switch(type) {
            case 'danger':
                toastType = 'error';
                break;
            case 'warning':
                toastType = 'warning';
                break;
            case 'success':
                toastType = 'success';
                break;
            default:
                toastType = 'info';
        }
        showMessage(message, toastType, 3000);
    } else {
        // 如果全局函数不可用，回退到原来的实现
        const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        
        $('.container-fluid').prepend(alertHtml);
        
        setTimeout(function() {
            $('.alert').alert('close');
        }, 3000);
    }
}

// 页面加载完成后自动加载清理历史
$(document).ready(function() {
    // 自动加载清理孤立任务执行历史
    loadCleanupHistory(1);
});
</script>
{% endblock %}